import { useUserStore } from '@/stores/user'

// 请求基础配置
const config = {
  // 根据环境设置baseURL
  baseURL: process.env.NODE_ENV === 'development' 
    ? 'http://localhost:3030/api' 
    : 'https://your-domain.com/api',
  timeout: 30000,
  header: {
    'Content-Type': 'application/json'
  }
}

// 请求拦截器
function requestInterceptor(options) {
  // 显示加载提示
  if (!options.hideLoading) {
    uni.showLoading({
      title: options.loadingText || '请求中...',
      mask: true
    })
  }
  
  // 添加token
  const userStore = useUserStore()
  const token = userStore.token
  if (token) {
    options.header = {
      ...options.header,
      'Authorization': `Bearer ${token}`
    }
  }
  
  // 添加请求时间戳（防止缓存）
  if (options.method === 'GET') {
    const timestamp = Date.now()
    const separator = options.url.includes('?') ? '&' : '?'
    options.url += `${separator}_t=${timestamp}`
  }
  
  return options
}

// 响应拦截器
function responseInterceptor(response, options) {
  // 隐藏加载提示
  if (!options.hideLoading) {
    uni.hideLoading()
  }
  
  const { statusCode, data } = response
  
  // HTTP状态码检查
  if (statusCode !== 200) {
    handleHttpError(statusCode)
    return Promise.reject(new Error(`HTTP Error: ${statusCode}`))
  }
  
  // 业务状态码检查
  if (data.code !== 200) {
    handleBusinessError(data)
    return Promise.reject(data)
  }
  
  return data
}

// 处理HTTP错误
function handleHttpError(statusCode) {
  let message = '网络异常'
  
  switch (statusCode) {
    case 400:
      message = '请求参数错误'
      break
    case 401:
      message = '未授权，请重新登录'
      handleTokenExpired()
      break
    case 403:
      message = '权限不足'
      break
    case 404:
      message = '请求的资源不存在'
      break
    case 500:
      message = '服务器内部错误'
      break
    case 502:
      message = '网关错误'
      break
    case 503:
      message = '服务不可用'
      break
    case 504:
      message = '网关超时'
      break
    default:
      message = `网络错误 ${statusCode}`
  }
  
  showError(message)
}

// 处理业务错误
function handleBusinessError(data) {
  const { code, message } = data
  
  switch (code) {
    case 401:
      // token失效
      handleTokenExpired()
      break
    case 403:
      showError('权限不足')
      break
    default:
      showError(message || '操作失败')
  }
}

// 处理token失效
function handleTokenExpired() {
  // 清除用户信息
  const userStore = useUserStore()
  userStore.logout()
  
  showError('登录已过期，请重新登录')
  
  // 跳转到登录页
  setTimeout(() => {
    uni.reLaunch({
      url: '/pages/login/login'
    })
  }, 1500)
}

// 显示错误信息
function showError(message) {
  uni.showToast({
    title: message,
    icon: 'none',
    duration: 2000
  })
}

// 统一请求方法
function request(options = {}) {
  return new Promise((resolve, reject) => {
    // 合并默认配置
    const requestOptions = {
      ...config,
      ...options,
      url: config.baseURL + options.url,
      header: {
        ...config.header,
        ...options.header
      }
    }
    
    // 请求拦截
    const interceptedOptions = requestInterceptor(requestOptions)
    
    // 发起请求
    uni.request({
      ...interceptedOptions,
      success: (response) => {
        try {
          const result = responseInterceptor(response, options)
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: (error) => {
        // 隐藏加载提示
        if (!options.hideLoading) {
          uni.hideLoading()
        }
        
        // 处理网络错误
        console.error('Request failed:', error)
        showError('网络连接失败，请检查网络设置')
        reject(error)
      }
    })
  })
}

// 导出请求方法
export default {
  // GET请求
  get(url, params = {}, options = {}) {
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&')
    
    return request({
      url: queryString ? `${url}?${queryString}` : url,
      method: 'GET',
      ...options
    })
  },
  
  // POST请求
  post(url, data = {}, options = {}) {
    return request({
      url,
      method: 'POST',
      data,
      ...options
    })
  },
  
  // PUT请求
  put(url, data = {}, options = {}) {
    return request({
      url,
      method: 'PUT',
      data,
      ...options
    })
  },
  
  // DELETE请求
  delete(url, options = {}) {
    return request({
      url,
      method: 'DELETE',
      ...options
    })
  },
  
  // 文件上传
  upload(url, filePath, options = {}) {
    return new Promise((resolve, reject) => {
      // 显示加载提示
      if (!options.hideLoading) {
        uni.showLoading({
          title: '上传中...',
          mask: true
        })
      }
      
      // 添加token
      const userStore = useUserStore()
      const token = userStore.token
      const header = token ? { 'Authorization': `Bearer ${token}` } : {}
      
      uni.uploadFile({
        url: config.baseURL + url,
        filePath,
        name: options.name || 'file',
        formData: options.formData || {},
        header,
        success: (response) => {
          // 隐藏加载提示
          if (!options.hideLoading) {
            uni.hideLoading()
          }
          
          try {
            const data = JSON.parse(response.data)
            if (data.code === 200) {
              resolve(data)
            } else {
              handleBusinessError(data)
              reject(data)
            }
          } catch (error) {
            showError('上传失败')
            reject(error)
          }
        },
        fail: (error) => {
          // 隐藏加载提示
          if (!options.hideLoading) {
            uni.hideLoading()
          }
          
          showError('上传失败')
          reject(error)
        }
      })
    })
  }
} 